#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash netcdf-c-4.9.0.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1
if [[ "$1" == "$2" ]]; then echo "构建路径与安装路径不能相同，请输入正确的路径"; exit 1; fi

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
set -e

download_pkg()
{
    wget -t 40 -c $1 -O $buildpath/netcdf-c-4.9.0.tar.gz
    tar xf $buildpath/netcdf-c-4.9.0.tar.gz -C $buildpath
    #rm -rf $buildpath/netcdf-c-4.9.0.tar.gz
}

download_pkg https://downloads.unidata.ucar.edu/netcdf-c/4.9.0/netcdf-c-4.9.0.tar.gz
cd $buildpath/netcdf-c-4.9.0
./configure CC=mpicc CXX=mpicxx --prefix=$installpath/netcdf-c-4.9.0 --enable-shared=yes --enable-static=yes --enable-largefile --enable-hdf5=yes --enable-pnetcdf LDFLAGS="-L$installpath/hdf5-1.12.1/lib -L$installpath/pnetcdf-1.12.3/lib" CPPFLAGS="-I$installpath/hdf5-1.12.1/include -I$installpath/pnetcdf-1.12.3/include"
make -j$(nproc)
make install

cat>"$installpath/netcdf-c-4.9.0/netcdf-c_modulefiles"<<EOF
#%Module1.0
conflict netcdf-c
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set netcdf [getModulefileDir]
setenv NETCDF \$netcdf
prepend-path PATH \$netcdf/bin
prepend-path LD_LIBRARY_PATH \$netcdf/lib
prepend-path INCLUDE \$netcdf/include
EOF

#rm -rf $buildpath/netcdf-c-4.9.0
